(* ===================================================================== *)
(** Application boptouch : creer rapidement des nouveaux projets en copiant
    des fichiers template présents dans $BEBOPDIR/template.
    @author Mathieu Barbin
    @version 1.0.* *)
(* ===================================================================== *)

open Bplib

(** chercher le template correspondant a une extension *)
let template = "template";;

let slach, copier =
  match Sys.os_type with
    | "Win32" -> "\\", "copy" 
    | _ -> "/", "cp";;

(** chercher template.ext dans templatedir et copier dans le repertoire courant avec le bon nom *)
let touch folder file option =
  if Sys.file_exists file
  then
    begin
      Printf.fprintf stderr "Cannot create file \"%s\", file already exists\n" file;
      flush stderr
    end
  else
  match split_file file with
  | "", _ | _, "" -> ()
  | name, ext ->
      (* cherche template.ext *)
      let template_file = 
        match option with
          | Some o -> Printf.sprintf "%s%s%s.%s.%s" folder slach template o ext
          | None -> Printf.sprintf "%s%s%s.%s" folder slach template ext
      in
      if Sys.file_exists template_file
      then 
	begin
	  Printf.fprintf stderr "Write file \"%s\"...\n" file;
	  ignore (Sys.command (Printf.sprintf "%s %s %s" copier template_file file));
	end
      else 
	begin
	  Printf.fprintf stderr "File \"%s\" Not Found\n" template_file;
	  flush stderr
	end

exception Arguments_Invalides

(* file * option *)
let exec_of_argv sysargv =
  let option = ref None in
  let file = ref "" in
  let file_done = ref false in
  let len = Array.length sysargv in
  let option_done = ref false in
  for i = 1 to pred len do
    let lenarg = String.length sysargv.(i) in
    if lenarg > 0 && sysargv.(i).[0] = '-'
    then 
      if !option_done then raise Arguments_Invalides
      else
        begin
          option_done := true;
          option := Some (String.sub sysargv.(i) 1 (pred lenarg)) 
        end
    else 
      if !file_done then raise Arguments_Invalides
      else
        begin
          file_done := true;
          file := sysargv.(i)
        end
  done;
  if not(!file_done) then raise Arguments_Invalides
  else (!file, !option);;

let _ = 
  Message.message#thisis "boptouch";
  Message.message#verbose_actif;
  try
    let file, option = exec_of_argv Sys.argv in
    let bebopdir = Printf.sprintf "%s%s%s" (Sys.getenv "BEBOPDIR") slach template in
    touch bebopdir file option 
  with
  | Arguments_Invalides ->
      Printf.fprintf stderr "use : %s [ -option ] [ myfile.bop | myfile.bpo | myfile.bpi | ... ]\n" Sys.argv.(0);
      flush stderr
  | Not_found ->
      Printf.fprintf stderr "Env-Var $BEBOPDIR Not found\n";
      flush stderr
